package com.sky.loveshop.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/9/1 11:15
 */
@Configuration
public class AlipayConfig {

    @Resource
    DataConfig dataConfig;

    @Bean
    public AlipayClient alipayClient() throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl(ZfbConstants.ZFB_ORDER_URL);
        //设置应用ID
        certAlipayRequest.setAppId(dataConfig.getZfbAppId());
        //设置应用私钥
        certAlipayRequest.setPrivateKey(dataConfig.getZfbAppPrivateKey());


        certAlipayRequest.setCertContent(getCertContentByPath(dataConfig.getZfbAppCertPath()));//设置应用公钥证书路径
        certAlipayRequest.setAlipayPublicCertContent(getCertContentByPath(dataConfig.getZfbAlipayPublicCertPath())); //设置支付宝公钥证书路径
        certAlipayRequest.setRootCertContent(getCertContentByPath(dataConfig.getZfbRootCertPath())); //设置支付根证书路径

//        certAlipayRequest.setCertPath(dataConfig.getZfbAppCertPath());//设置应用公钥证书路径
//        certAlipayRequest.setAlipayPublicCertPath(dataConfig.getZfbAlipayPublicCertPath()); //设置支付宝公钥证书路径
//        certAlipayRequest.setRootCertPath(dataConfig.getZfbRootCertPath());  //设置支付根证书路径

        //设置请求格式，固定值json
        certAlipayRequest.setFormat("JSON");
        //设置字符集
        certAlipayRequest.setCharset("UTF-8");
        //生成签名字符串所使用的签名算法类型
        certAlipayRequest.setSignType("RSA2");
        //实例化客户端
        return new DefaultAlipayClient(certAlipayRequest);
    }

    public String getCertContentByPath(String name) {
        InputStream inputStream = null;
        String content = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource(name);
            inputStream = classPathResource.getInputStream();
            content = new String(FileCopyUtils.copyToByteArray(inputStream));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

}
